package cn.wolfcode.web.controller;


import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.News;
import cn.wolfcode.enums.NewsEnums;
import cn.wolfcode.qo.NewsObject;
import cn.wolfcode.service.INewsService;
import cn.wolfcode.util.RequiredPermission;
import cn.wolfcode.util.UserContext;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/news")
public class NewsController {

    @Autowired
    private INewsService newsService;


    @RequiredPermission(name = "公告管理表页面", expression = "news:list")
    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") NewsObject qo) {
        //获取当前登录用户,然后去页面把不需要的按钮给隐藏起来
        Employee currentUser = UserContext.getCurrentUser();
        model.addAttribute("currentUser", currentUser);
        //遍历所有枚举
        model.addAttribute("newsEnums", NewsEnums.values());
        //判断是否是管理员,如果是那就可以查看所有的公告,如果不是那就只能查看已发布的公告
        if (currentUser.isAdmin()) {
            PageInfo<News> pageInfo = newsService.query(qo);
            model.addAttribute("pageInfo", pageInfo);
        } else {
            model.addAttribute("pageInfo", newsService.selectList(qo));
        }
        return "news/list";
    }


    @RequiredPermission(name = "公告管理表删除", expression = "news:delete")
    @RequestMapping("/delete")
    public String delete(Long id) {
        if (id != null) {
            newsService.delete(id);
        }
        return "redirect:/news/list";
    }


    @RequiredPermission(name = "公告管理表新增/编辑", expression = "news:saveOrUpdate")
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(News news) {
        if (news.getId() == null) {
            newsService.save(news);
        } else {
            newsService.update(news);
        }
        return "redirect:/news/list";
    }

    @RequiredPermission(name = "公告管理表新增/编辑", expression = "news:saveOrUpdate")
    @RequestMapping("/input")
    public String input(Long id, Model model) {
        if (id != null) {
            model.addAttribute("news", newsService.get(id));
        }
        return "news/input";
    }

    @RequestMapping("/show")
    public String show(Model model, Long id) {
        //通过这个方法去修改查看的状态,前台把id给带过来
        newsService.updateisRead(id);
        model.addAttribute("shows", newsService.get(id));
        return "news/show";

    }

    @RequestMapping("/statuss")
    public String statuss(Long id) {
        //通过这个方法去修改发布状态,前台把id带过来
        newsService.updateOne(id);
        return "redirect:/news/list";
    }
}
